import { BrowserWindow } from 'electron';
import { join, resolve } from 'path';
import { parse } from 'url';
import config from './config';

export default function create_main_window() {
	const { main, maximizable } = config('APP');
	const url = (() => {
		const p = parse(main);
		if (!p.protocol) {
			return join('file://', resolve(main));
		} else {
			return main;
		}
	})();
	const win = new BrowserWindow({
		maximizable,
		titleBarStyle: 'hiddenInset',
		webPreferences: {
			nodeIntegrationInWorker: true
		}
	});

	// and load the index.html of the app.
	win.loadURL(url);

	// Open the DevTools.
	if (config('debug')) {
		win.webContents.openDevTools();
	}

	// Emitted when the window is closed.
	win.on('closed', () => {
		// Dereference the window object, usually you would store windows
		// in an array if your app supports multi windows, this is the time
		// when you should delete the corresponding element.
		(global as any).main_win = null;
	});
	if (maximizable) {
		win.maximize();
	}
	(global as any).main_win = win;
	return win;
}
